/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.scene.domain.PreShiftMeeting;
import com.koron.scene.domain.PreShiftMeetingTeamMember;
import com.koron.scene.mapper.PreShiftMeetingMapper;
import com.koron.scene.service.api.PreShiftMeetingService;
import com.koron.scene.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PreShiftMeetingServiceImpl implements PreShiftMeetingService {

    private final static Logger logger = LoggerFactory.getLogger(PreShiftMeetingServiceImpl.class);
    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private Util util;

    @Override
    public MessageBean<Integer> save(PreShiftMeeting bean, List<PreShiftMeetingTeamMember> teamMemberList, String keepFiles, String delFiles, MultipartFile[] files, StaffBean user) {
        MessageBean msg = new MessageBean();
        List<String> keepFileList = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    //获得文件名
                    String fileName = file.getOriginalFilename();
                    //文件上传
                    String url = clientWrapper.uploadFile(file);
                    keepFileList.add(url + "#" + fileName);
                }
            }
            if (StringUtils.isEmpty(bean.getId())) {
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                if (null != keepFileList && keepFileList.size() > 0) {
                    bean.setAttachment(new Gson().toJson(keepFileList));
                }
                Integer insert = factory.getMapper(PreShiftMeetingMapper.class).insert(bean);
                if (insert > 0) {
                    if (null != teamMemberList && teamMemberList.size() > 0) {
                        for (PreShiftMeetingTeamMember teamMember : teamMemberList) {
                            teamMember.setId(DefaultIdGenerator.getInstance().generateLongId());
                            teamMember.setPreShiftMeetingId(bean.getId());
                        }
                        insert = factory.getMapper(PreShiftMeetingMapper.class).batchInsert(teamMemberList);
                    }
                }
                if (insert > 0) {
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("保存成功");
                } else {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("保存失败");
                }
                return msg;
            } else {
                if (StringUtils.isNotEmpty(keepFiles)) {
                    String[] keepArray = keepFiles.split("[;；]");
                    keepFileList.addAll(Arrays.asList(keepArray));
                }
                if (null != keepFileList && keepFileList.size() > 0) {
                    bean.setAttachment(new Gson().toJson(keepFileList));
                }
                PreShiftMeeting entity = factory.getMapper(PreShiftMeetingMapper.class).queryOne(bean.getId());
                if (null == entity) {
                    msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getDescription());
                    return msg;
                }
                if (entity.getStatus() != 0) {
                    msg.setCode(BusinessCode.NON_DRAFT_CANNOT_EDIT.getCode());
                    msg.setDescription(BusinessCode.NON_DRAFT_CANNOT_EDIT.getDescription());
                    return msg;
                }
                Integer insert = factory.getMapper(PreShiftMeetingMapper.class).update(bean);
                if (insert > 0) {
                    // 先删除原有的班组成员
                    Integer delete = factory.getMapper(PreShiftMeetingMapper.class).deleteTeamMemberByMeetId(bean.getId());
                    // 再将修改后的班组成员加入数据库
                    if (null != teamMemberList && teamMemberList.size() > 0) {
                        for (PreShiftMeetingTeamMember teamMember : teamMemberList) {
                            teamMember.setId(DefaultIdGenerator.getInstance().generateLongId());
                            teamMember.setPreShiftMeetingId(bean.getId());
                        }
                        factory.getMapper(PreShiftMeetingMapper.class).batchInsert(teamMemberList);
                    }
                    if (StringUtils.isNotEmpty(delFiles)) {
                        String[] delArray = delFiles.split("[;；]");
                        for (String delUrl : delArray) {
                            clientWrapper.deleteFile(delUrl.split("#")[0]);
                        }
                    }
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("修改成功");
                    return msg;
                } else {
                    if (null != keepFileList && keepFileList.size() > 0) {
                        if (StringUtils.isEmpty(keepFiles)) {
                            for (String url : keepFileList) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        } else {
                            List<String> keeps = Arrays.asList(keepFiles.split("[;；]"));
                            for (String url : keepFileList) {
                                if (!keeps.contains(url)) {
                                    clientWrapper.deleteFile(url.split("#")[0]);
                                }
                            }
                        }
                    }
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("修改失败");
                    return msg;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            if (null != keepFileList && keepFileList.size() > 0) {
                for (String url : keepFileList) {
                    clientWrapper.deleteFile(url.split("#")[0]);
                }
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("保存失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(String id, StaffBean user) {
        MessageBean msg = new MessageBean();
        SessionFactory factory = new SessionFactory();
        try {
            PreShiftMeeting meeting = factory.getMapper(PreShiftMeetingMapper.class).queryOne(id);
            if (null == meeting) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getDescription());
                return msg;
            }
            if (meeting.getStatus() != 0) {
                msg.setCode(BusinessCode.NON_DRAFT_CANNOT_DELETE.getCode());
                msg.setDescription(BusinessCode.NON_DRAFT_CANNOT_DELETE.getDescription());
                return msg;
            }
            Integer insert = factory.getMapper(PreShiftMeetingMapper.class).delete(id);
            if (insert > 0) {
                factory.getMapper(PreShiftMeetingMapper.class).deleteTeamMemberByMeetId(id);
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("删除失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<PreShiftMeeting> queryOne(String id) {
        MessageBean msg = new MessageBean();
        SessionFactory factory = new SessionFactory();
        try {
            PreShiftMeeting meeting = factory.getMapper(PreShiftMeetingMapper.class).queryOne(id);
            if (null == meeting) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getDescription());
                return msg;
            }
            List<PreShiftMeetingTeamMember> teamMemberList = factory.getMapper(PreShiftMeetingMapper.class).getTeamMembersByPreShiftMeetingId(id);
            meeting.setTeamMemberList(teamMemberList);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询班前会详情成功");
            msg.setData(meeting);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("查询失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<DataBean<PreShiftMeeting>> list(StaffBean user, String corpCode, String teamName, Integer start, Integer pageSize, String keyword, Integer containSub) {
        MessageBean<DataBean<PreShiftMeeting>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            StringBuilder codes = new StringBuilder("");
            if (containSub !=null && containSub == 1) {
                codes.append(util.getDeptCodes(corpCode));
            } else {
                codes.append("('").append(corpCode).append("')");
            }
            List<PreShiftMeeting> list = factory.getMapper(PreShiftMeetingMapper.class).queryByCondition(user.getCode(),codes.toString(), teamName, start, pageSize,keyword);
            Integer totalNumber = factory.getMapper(PreShiftMeetingMapper.class).countByCondition(user.getCode(),codes.toString(), teamName,keyword);
            Integer totalPage = (totalNumber > pageSize) ? (totalNumber % pageSize == 0 ? totalNumber / pageSize : totalNumber / pageSize + 1) : 1;
            DataBean<PreShiftMeeting> dataBean = new DataBean<>();
            for (PreShiftMeeting meeting : list) {
                List<PreShiftMeetingTeamMember> teamMemberList = factory.getMapper(PreShiftMeetingMapper.class).getTeamMembersByPreShiftMeetingId(meeting.getId());
                meeting.setTeamMemberList(teamMemberList);
            }
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(pageSize);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询班前会列表成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> preShiftMeetingToImage(String id) {
        MessageBean msg = new MessageBean();
        SessionFactory factory = new SessionFactory();
        try {
            PreShiftMeeting meeting = factory.getMapper(PreShiftMeetingMapper.class).queryOne(id);
            if (null == meeting) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getDescription());
                return msg;
            }
            Map<String, Object> map = new HashMap<>();
            String name = "班组名称：" + meeting.getTeamName() + ",时间：" + meeting.getMeetingTime() + "值班长：" +
                    meeting.getShiftForemanName();
            String text = meeting.getId();
            map.put("text", text);
            map.put("name", name);
            msg.setData(map);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("签到失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<?> preShiftMeetingToCheckIn(StaffBean user, String id, MultipartFile file) {
        MessageBean msg = new MessageBean();
        SessionFactory factory = new SessionFactory();
        try {
            PreShiftMeeting meeting = factory.getMapper(PreShiftMeetingMapper.class).queryOne(id);
            if (null == meeting) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getDescription());
                return msg;
            }
            // 获取班前会班组成员
            List<PreShiftMeetingTeamMember> memberList = factory.getMapper(PreShiftMeetingMapper.class).getTeamMembersByPreShiftMeetingId(id);
            List<String> collect = memberList.stream().map(preShiftMeetingTeamMember -> preShiftMeetingTeamMember.getMemberCode()).collect(Collectors.toList());
            if (!collect.contains(meeting.getShiftForeman())) {
                collect.add(meeting.getShiftForeman());
            }
            if (!collect.contains(user.getCode())) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_SIGN_IN.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_SIGN_IN.getDescription());
                return msg;
            }
            // 根据当前操作人和班前会id查找班组信息
            PreShiftMeetingTeamMember teamMember = factory.getMapper(PreShiftMeetingMapper.class).queryMember(id, user.getCode());
            if (null == teamMember) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_SIGN_IN_FAILURE.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_SIGN_IN_FAILURE.getDescription());
                return msg;
            }
//            if (null != teamMember.getCheckInStatus() && teamMember.getCheckInStatus() == 1 && StringUtils.isNotEmpty(teamMember.getSignAttachment())) {
//                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_SIGN_EXIST.getCode());
//                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_SIGN_EXIST.getDescription());
//                return msg;
//            }
            String signAttachment = null;
            if (null != file && !file.isEmpty()) {
                //获得文件名
                String fileName = file.getOriginalFilename();
                //文件上传
                String url = clientWrapper.uploadFile(file);
                signAttachment = url + "#" + fileName;
            }
            teamMember.setCheckInStatus(1);
            teamMember.setSignAttachment(signAttachment);
            Integer integer = factory.getMapper(PreShiftMeetingMapper.class).updateTeamMember(teamMember);
            if (integer > 0) {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("签到成功");
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("签到失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("签到失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public Map export(String id, InputStream inputStream) {
        Map map = new HashMap();
        // 获取班前会数据
        MessageBean<PreShiftMeeting> msg = queryOne(id);
        PreShiftMeeting meeting = null;
        if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
            if (null != msg.getData()) {
                meeting = msg.getData();
            }
        }
        if (null == meeting) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String str = meeting.getSafetyPrecautions();
        if (StringUtils.isNotEmpty(str)) {
            // 通过String.valueOf((char)10)对excel进行文本换行操作
            String replace = str.replace("↵", String.valueOf((char) 10));
            meeting.setSafetyPrecautions(replace);
        }
        String meetTime = simpleDateFormat.format(meeting.getMeetingTime());
        meeting.setMeetTime(meetTime);
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
            // 导出班前会数据
            if (null != meeting) {
                CellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                cellStyle.setWrapText(true);
                XSSFSheet sheet = workbook.getSheetAt(0);
                // 设置班前会内容
                XSSFRow row;
                row = sheet.getRow(1);
                row.getCell(2).setCellValue(meeting.getTeamName());
                map.put("teamName", meeting.getTeamName());
                row.setRowStyle(cellStyle);
                row = sheet.getRow(1);
                row.getCell(4).setCellValue(meeting.getShiftForemanName());
                row.setRowStyle(cellStyle);
                row = sheet.getRow(2);
                row.getCell(2).setCellValue(meeting.getMeetTime());
                row.getCell(4).setCellValue(meeting.getExplains());
                row.setRowStyle(cellStyle);
                row = sheet.getRow(3);
                row.getCell(2).setCellValue(meeting.getSafetyPrecautions());
                row.setRowStyle(cellStyle);
                int rowNum = 5;
                // 设置班组成员数据
                List<PreShiftMeetingTeamMember> memberList = meeting.getTeamMemberList();
                if (null != memberList && memberList.size() > 0) {
                    int index = 1;
                    for (PreShiftMeetingTeamMember member : memberList) {
                        row = sheet.getRow(rowNum);
                        row.getCell(1).setCellValue(member.getMemberName());
                        // 合并单元格
                        // 指定 4 个参数，起始行，结束行，起始列，结束列。然后这个区域将被合并
//                        CellRangeAddress region = new CellRangeAddress(rowNum, rowNum, 1, 2);
//                        sheet.addMergedRegion(region);
                        // 获取签到图片
                        if (StringUtils.isNotEmpty(member.getSignAttachment())) {
                            XSSFDrawing drawing = sheet.createDrawingPatriarch();
                            String signAttachment = member.getSignAttachment();
                            String url = signAttachment.split("#")[0];
                            if (null != url) {
                                URL imgUrl = new URL(url);
                                String suffix = url.substring(url.lastIndexOf(".") + 1);
                                BufferedImage bufferImg = ImageIO.read(imgUrl);
                                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                                ImageIO.write(bufferImg, suffix, byteArrayOut);
                                XSSFClientAnchor anchor = new XSSFClientAnchor(1, 1, 1, 1, 5, rowNum, 6, rowNum + 1);
                                //插入图片
                                drawing.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                            }
                        }
                        index++;
                        rowNum++;
                    }
                }
            }
            map.put("workbook", workbook);
            return map;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public List<PreShiftMeeting> exportList(StaffBean user, String corpCode, String teamName, Integer containSub) {
        try (SessionFactory factory = new SessionFactory()) {
            StringBuilder codes = new StringBuilder("");
            if (containSub !=null && containSub == 1) {
                codes.append(util.getDeptCodes(corpCode));
            } else {
                codes.append("('").append(corpCode).append("')");
            }
            List<PreShiftMeeting> list = factory.getMapper(PreShiftMeetingMapper.class).queryByCondition(user.getCode(), codes.toString(), teamName, null, null,null);
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list.forEach(bean -> {
                    if (StringUtils.isNotEmpty(bean.getCorpCode())) {
                        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                        Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                        bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                                ? null : map.get(bean.getCorpCode()));
                    }
                    if (null != bean.getMeetingTime()) {
                        bean.setMeetTime(sdf.format(bean.getMeetingTime()));
                    }
                });
            }
            factory.close();
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public MessageBean<?> supplementFile(StaffBean user, String id, MultipartFile file) {
        MessageBean msg = new MessageBean();
        SessionFactory factory = new SessionFactory();
        String attachmentUrl = null;
        try {
            PreShiftMeeting meeting = factory.getMapper(PreShiftMeetingMapper.class).queryOne(id);

            if (null == meeting) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getDescription());
                return msg;
            }
            if (null != file && !file.isEmpty()) {
                //获得文件名
                String fileName = file.getOriginalFilename();
                //文件上传
                String url = clientWrapper.uploadFile(file);
                attachmentUrl = url + "#" + fileName;
            }
            String attachment = meeting.getAttachment();
            List<String> list = new ArrayList<>();
            if (StringUtils.isNotEmpty(attachment)) {
                list = JSONObject.parseArray(attachment, String.class);
            }
            list.add(attachmentUrl);
            meeting.setAttachment(new Gson().toJson(list));
            Integer update = factory.getMapper(PreShiftMeetingMapper.class).update(meeting);
            if (update > 0) {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("保存成功");
                msg.setData(attachmentUrl);
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != attachmentUrl) {
                clientWrapper.deleteFile(attachmentUrl.split("#")[0]);
            }
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("保存失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<?> deleteFile(StaffBean user, String id, String fileUrl) {
        MessageBean msg = new MessageBean();
        SessionFactory factory = new SessionFactory();
        try {
            PreShiftMeeting meeting = factory.getMapper(PreShiftMeetingMapper.class).queryOne(id);
            if (null == meeting) {
                msg.setCode(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.PRE_SHIFT_MEETING_NOT_EXIST.getDescription());
                return msg;
            }
            String attachment = meeting.getAttachment();
            List<String> list = null;
            if (StringUtils.isNotEmpty(attachment)) {
                list = JSONObject.parseArray(attachment, String.class);
                if (null != list && list.contains(fileUrl)) {
                    list.remove(fileUrl);
                }
            }
            meeting.setAttachment(null != list && list.size() > 0 ? new Gson().toJson(list) : new Gson().toJson(new ArrayList<>()));
            Integer update = factory.getMapper(PreShiftMeetingMapper.class).update(meeting);
            if (update > 0) {
                clientWrapper.deleteFile(fileUrl.split("#")[0]);
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("删除失败");
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }
}
